package com.wang.xh.gateway.filter;

import com.wang.xh.gateway.config.MyConfig;
import com.wang.xh.gateway.domain.AuthUser;
import com.wang.xh.gateway.properties.JwtProperties;
import com.wang.xh.common.constants.Constants;
import com.wang.xh.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

/**
 * @author wjh
 * @create 2024-09-07 18:59
 */
@Slf4j
@Component
public class CustomerTokenGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> implements AuthFilter {
    
    @Resource
    private MyConfig myConfig;
    @Resource
    private JwtProperties jwtProperties;
    
    
    @Override
    public AuthUser check(String token) {
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            String openId = claims.get(Constants.GATEWAY.OPEN_ID).toString();
            AuthUser authUser = new AuthUser();
            authUser.setOpenId(openId);
            return authUser;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Boolean auth(String token, AuthUser authAuthUserInfo, String path) {
        //普通用户不需要权限校验
        return true;
    }

    @Override
    public GatewayFilter apply(Object config) {
        return new TokenGatewayFilter(this.myConfig, this);
    }

    @Override
    public String tokenHeaderName() {
        return Constants.GATEWAY.ACCESS_TOKEN;
    }
}
